import { demoApi, TABLE_INDEX, normalizeResponse } from './client';

const COURSE_CATEGORY_TYPE = '课程';

const pickData = (response) => normalizeResponse(response) ?? [];

export async function registerUser(form) {
  const data = await demoApi.register(form);
  return normalizeResponse(data);
}

export async function loginUser(form) {
  const data = await demoApi.login(form);
  return normalizeResponse(data);
}

export async function fetchCourseCategories() {
  const response = await demoApi.getAll({
    typeIndex: TABLE_INDEX.categories,
    categoryType: COURSE_CATEGORY_TYPE,
  });
  const list = pickData(response);
  return Array.isArray(list) ? list : [];
}

export async function createCourseCategory(payload) {
  const response = await demoApi.addItem({
    ...payload,
    typeIndex: TABLE_INDEX.categories,
    categoryType: COURSE_CATEGORY_TYPE,
  });
  return normalizeResponse(response);
}

export async function fetchCourses(params = {}) {
  const response = await demoApi.getAll({
    typeIndex: TABLE_INDEX.courses,
    ...params,
  });
  const list = pickData(response);
  return Array.isArray(list) ? list : [];
}

export async function createCourse(payload) {
  const response = await demoApi.addItem({
    ...payload,
    typeIndex: TABLE_INDEX.courses,
  });
  return normalizeResponse(response);
}

export async function fetchCourseDetail(id) {
  const response = await demoApi.getSingle({
    typeIndex: TABLE_INDEX.courses,
    id,
  });
  return normalizeResponse(response);
}

export async function fetchCourseTasks(courseId) {
  const response = await demoApi.getAll({
    typeIndex: TABLE_INDEX.subitems,
    parentid: courseId,
  });
  const list = pickData(response);
  return Array.isArray(list) ? list : [];
}

export async function createCourseTask(payload) {
  const response = await demoApi.addItem({
    ...payload,
    typeIndex: TABLE_INDEX.subitems,
    parentType: COURSE_CATEGORY_TYPE,
  });
  return normalizeResponse(response);
}

export async function fetchCourseComments(courseId) {
  const response = await demoApi.getAll({
    typeIndex: TABLE_INDEX.comments,
    articleid: courseId,
    replyType: COURSE_CATEGORY_TYPE,
  });
  const list = pickData(response);
  return Array.isArray(list) ? list : [];
}

export async function createCourseComment(payload) {
  const response = await demoApi.addItem({
    ...payload,
    typeIndex: TABLE_INDEX.comments,
    replyType: COURSE_CATEGORY_TYPE,
  });
  return normalizeResponse(response);
}
